package com.hmdp.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.constants.SystemConstants;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.constants.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    CacheClient cacheClient;
    private ExecutorService ThreadPool  = Executors.newFixedThreadPool(1);
    public boolean tryLock(String key){
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, ",", LOCK_SHOP_TTL, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(result);
    }
    public void unLock(String key){
        stringRedisTemplate.delete(key);
    }
    //  缓存预热
    public void saveShop2Redis(long id, long expireSeconds ){
        // 1、查数据
        Shop shop = getById(id);
        // 2、添加额外过期字段
        RedisData<Shop> shopRedisData = new RedisData<>();
        shopRedisData.setData(shop);
        shopRedisData.setExipireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3、保存到redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(shopRedisData));
    }
    @Override
    public Result queryById(Long id) {
//        Shop shop = cacheClient.queryWitchPassThrough(CACHE_SHOP_KEY, id, Shop.class, sid -> getById(sid), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20, TimeUnit.SECONDS);
//        Shop shop = queryWithLogicalExpire(id);
        return Result.ok(shop);
    }
    public Shop queryWithLogicalExpire(long id){
        Shop shop;
        // 1、先查缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 1.1 判断缓存是否命中，如果未命中，说明不是热点key
        if(StrUtil.isBlank(shopJson)){
            return null;
        }
        // 1.2 缓存命中，还需要判断是否逻辑过期
        RedisData<Shop> redisData = JSONUtil.toBean(shopJson, new TypeReference<RedisData<Shop>>() {}, false);
        shop = redisData.getData();
        if(shop!=null && redisData.getExipireTime().isAfter(LocalDateTime.now())){
            // 未过期直接返回
            return shop;
        }
        // 2、缓存逻辑过期，重建
        boolean islock  = tryLock(LOCK_SHOP_KEY+id);
        if(islock){
            ThreadPool.submit(()->{
                try {
                    Thread.sleep(200); //模拟重建延迟
                    this.saveShop2Redis(id, 10);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    unLock(LOCK_SHOP_KEY+id);
                }
            });
        }
        return shop; //返回旧数据
    }
    public Shop queryWithMutex(long id){
        // 1、先查缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 缓存失效包含 null 和 空字符串 两种情况
        if(shopJson != null){
            // 说明此时是空字符串，请求的是不存在的id
            return null;
        }
        // 2、缓存击穿的解决，避免所有查询都走数据库
        Shop shop;
        try {
            boolean islock  = tryLock(LOCK_SHOP_KEY+id);
            if(!islock){
                Thread.sleep(50);
                //其实这里做了double check, 加锁失败休眠醒来可能其他的线程已经重建好了缓存
                return queryWithMutex(id);
            }
            // 3、缓存失效直接查数据库
            shop = getById(id);
            // 休眠200毫秒模拟重建延迟
            Thread.sleep(200);
            // 4. 数据库也没有返回空对象给Redis(避免缓存穿透）
            if(shop==null){
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 5、数据查询后更新缓存
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            unLock(LOCK_SHOP_KEY+id);
        }
        return shop;
    }
    public Result queryWithThrough(Long id) {
        // 未作缓存击穿的解决
        // 1、先查缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        // 缓存失效包含 null 和 空字符串 两种情况
        if(shopJson != null){
            // 说明此时是空字符串，请求的是不存在的id
            return Result.fail("店铺不存在！");
        }
        // 2、缓存失效直接查数据库
        Shop shop = getById(id);
        // 3. 数据库也没有返回空对象给Redis(避免缓存穿透）
        if(shop==null){
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("店铺不存在！");
        }
        // 4、数据查询后更新缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    @Transactional
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id==null)
            return Result.fail("商铺id不能为空");
        // 1、先存数据库
        updateById(shop);
        // 2、再删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        // 注意两者原子性
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if(x == null || y==null) {
            // 根据类型分页查询
            Page<Shop> page = query().eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 0.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 1、根据typeId和经纬度查Redis
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(new Point(x, y)),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if(search == null) return Result.ok();
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = search.getContent();
        if(list.size() < from)
            return Result.ok(Collections.emptyList());
        // 2、解析数据
        List<Long> ids = new ArrayList<>();
        Map<String, Distance> distanceMap = new HashMap<>();
        // 分页查询，截取from到end部分
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 3、根据店铺id查询具体信息（店铺实体设置了额外字段 距离）
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(" + idStr + ")").list().stream().map(
                shop -> shop.setDistance(distanceMap.get(shop.getId().toString()).getValue())
        ).collect(Collectors.toList());
        return Result.ok(shops);
    }
}
